<template>
  <div class="app-container">
    <el-card class="form-card">
      <div slot="header" class="card-header">
        <h3>{{ isEdit ? '编辑项目' : '发起科研项目' }}</h3>
        <el-button @click="goBack">返回</el-button>
      </div>

      <el-form ref="projectForm" :model="form" :rules="rules" label-width="120px" class="project-form"
        v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入项目标题" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请详细描述项目内容、目标和预期成果"
                maxlength="500" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="form.startDate" type="date" placeholder="选择开始日期" style="width: 100%"
                value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期" style="width: 100%"
                value-format="yyyy-MM-dd" :picker-options="endDateOptions" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="邀请学生">
              <el-select v-model="form.studentIds" multiple placeholder="请选择学生" style="width: 100%" :disabled="isEdit">
                <el-option v-for="student in studentOptions" :key="student.id"
                  :label="`${student.username} (${student.account})`" :value="student.id" />
              </el-select>
              <div class="form-tip">
                {{ isEdit ? '编辑模式下无法修改邀请学生，请在项目详情页面管理团队成员' : '可以稍后在项目详情页面邀请更多学生' }}
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目附件">
              <el-upload ref="upload" class="upload-demo" drag action="#" :file-list="attachmentFileList"
                :on-preview="handleAttachmentPreview" :on-remove="handleAttachmentRemove"
                :before-upload="beforeAttachmentUpload" :on-exceed="handleAttachmentExceed"
                :http-request="handleAttachmentUpload" multiple :limit="5"
                accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">
                  支持上传PDF、Word、Excel、PPT等文件，单个文件不超过10MB，最多上传5个文件
                </div>
              </el-upload>

              <!-- 文件预览列表 -->
              <div v-if="attachmentFileList.length > 0" class="file-list-preview">
                <div v-for="(file, index) in attachmentFileList" :key="index" class="file-item">
                  <i :class="getFileIcon(file.fileType)" class="file-icon" />
                  <span class="file-name">{{ file.name }}</span>
                  <span class="file-size">({{ formatFileSize(file.size) }})</span>
                  <span v-if="file.status" class="file-status" :class="file.status">
                    {{ file.status === 'success' ? '上传成功' : file.status === 'uploading' ? '上传中...' : '上传失败' }}
                  </span>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="handleSubmit" :loading="submitting">
                {{ isEdit ? '更新项目' : '创建项目' }}
              </el-button>
              <el-button @click="goBack">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { createProject, updateProject, getProjectDetail } from '@/api/research'
import { uploadFile } from '@/api/upload'
import { getStudents } from '@/api/user'

export default {
  name: 'CreateProject',
  data() {
    return {
      isEdit: false,
      projectId: null,
      submitting: false,
      loading: false,
      form: {
        title: '',
        description: '',
        startDate: '',
        endDate: '',
        studentIds: []
      },
      studentOptions: [],

      // 附件上传相关
      attachmentFileList: [],

      rules: {
        title: [
          { required: true, message: '请输入项目标题', trigger: 'blur' },
          { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入项目描述', trigger: 'blur' },
          { min: 20, max: 500, message: '描述长度在 20 到 500 个字符', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    endDateOptions() {
      return {
        disabledDate: (time) => {
          if (this.form.startDate) {
            return time.getTime() <= new Date(this.form.startDate).getTime()
          }
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  created() {
    // 检查是否为编辑模式
    if (this.$route.query.id) {
      this.isEdit = true
      this.projectId = parseInt(this.$route.query.id)
      this.loadProjectData()
    }

    this.getStudentsList();
  },
  methods: {
    // 加载项目数据（编辑模式）
    async loadProjectData() {
      this.loading = true
      try {
        console.log('加载项目数据，项目ID:', this.projectId)
        const response = await getProjectDetail(this.projectId)

        if (response.code === 200 && response.data) {
          const projectData = response.data
          console.log('获取到的项目数据:', projectData)

          // 填充表单数据
          this.form = {
            title: projectData.title || '',
            description: projectData.description || '',
            startDate: projectData.startDate || '',
            endDate: projectData.endDate || '',
            studentIds: this.extractStudentIds(projectData),
            status: projectData.status || 0
          }

          // 处理附件数据
          if (projectData.attachmentUrls && typeof projectData.attachmentUrls === 'string') {
            try {
              this.attachmentFileList = JSON.parse(projectData.attachmentUrls)
              console.log('解析的附件列表:', this.attachmentFileList)
            } catch (e) {
              console.error('解析附件数据失败:', e)
              this.attachmentFileList = []
            }
          } else if (projectData.attachments && Array.isArray(projectData.attachments)) {
            this.attachmentFileList = projectData.attachments
          } else {
            this.attachmentFileList = []
          }

          console.log('表单数据已填充:', this.form)
        } else {
          console.error('获取项目详情失败:', response)
          this.$message.error('获取项目详情失败')
          this.goBack()
        }
      } catch (error) {
        console.error('加载项目数据失败:', error)
        this.$message.error('加载项目数据失败，请重试')
        this.goBack()
      } finally {
        this.loading = false
      }
    },

    // 提取学生ID数组
    extractStudentIds(projectData) {
      // 如果直接有studentIds数组
      if (projectData.studentIds && Array.isArray(projectData.studentIds)) {
        return projectData.studentIds
      }

      // 如果有teamMembers数组，提取学生成员的ID
      if (projectData.teamMembers && Array.isArray(projectData.teamMembers)) {
        return projectData.teamMembers
          .filter(member => member.role === 'student')
          .map(member => member.id)
      }

      // 如果有members数组
      if (projectData.members && Array.isArray(projectData.members)) {
        return projectData.members
          .filter(member => member.role === 'student')
          .map(member => member.id)
      }

      return []
    },

    // 获取所有学生信息
    async getStudentsList() {
      try {
        const response = await getStudents();
        if (response.code === 200 && response.data) {
          this.studentOptions = response.data;
          console.log('获取学生列表:', this.studentOptions);
        } else {
          this.studentOptions = [];
          console.error('获取学生列表失败:', response);
        }
      } catch (error) {
        console.error('获取学生列表失败:', error);
        this.studentOptions = [];
      }
    },


    // 提交表单
    async handleSubmit() {
      this.$refs.projectForm.validate(async (valid) => {
        if (valid) {
          this.submitting = true

          try {
            // 准备请求参数
            const requestParams = {
              title: this.form.title,
              description: this.form.description,
              startDate: this.form.startDate,
              endDate: this.form.endDate,
              status: this.isEdit ? this.form.status : 0, // 新建项目默认状态为0
              studentIds: this.form.studentIds || [], // 邀请的学生ID集合
              fileUrl: JSON.stringify(this.attachmentFileList) // 附件信息
            }

            // 如果是编辑模式，添加项目ID
            if (this.isEdit) {
              requestParams.id = this.projectId
            }
            if (this.form.studentIds && this.form.studentIds.length > 0) {
              const selectedStudents = this.studentOptions.filter(student =>
                this.form.studentIds.includes(student.id)
              );
              console.table(selectedStudents.map(student => ({
                ID: student.id,
                姓名: student.username,
                学号: student.account,
                手机: student.phone
              })));
            } else {
              console.log('未邀请学生');
            }
            console.log('📎 附件信息:')

            // 发起API请求
            let response
            if (this.isEdit) {
              console.log('发起更新项目请求...')
              response = await updateProject(requestParams)
            } else {
              console.log('发起创建项目请求...')
              response = await createProject(requestParams)
            }
            const action = this.isEdit ? '更新' : '创建'
            this.$message.success(`项目${action}成功！`)
            this.goBack()

          } catch (error) {
            console.log(error);
            this.submitting = false;
          }
        } else {
          this.$message.error('表单验证失败')
        }
      })
    },

    // 返回列表页
    goBack() {
      this.$router.push('/research/projects')
    },

    // 文件上传相关方法
    async handleAttachmentUpload(options) {
      const formData = new FormData()
      formData.append('file', options.file)

      try {
        const response = await uploadFile(formData)
        if (response.code === 200 && response.data) {
          const fileData = {
            name: response.data.name,
            url: response.data.url,
            fileType: response.data.fileType,
            size: options.file.size,
            originalName: options.file.name,
            status: 'success',
            uid: options.file.uid,
            uploadTime: Date.now(),
            responseCode: response.code,
            responseMsg: response.msg,
            responseMap: response.map
          }

          // 更新文件列表中的对应文件
          const fileIndex = this.attachmentFileList.findIndex(item => item.uid === options.file.uid)
          if (fileIndex !== -1) {
            this.attachmentFileList.splice(fileIndex, 1, fileData)
          }

          this.$message.success(`文件 ${options.file.name} 上传成功`)
          console.log('文件上传成功:', fileData)
        } else {
          this.$message.error('文件上传失败')
          // 移除失败的文件
          this.attachmentFileList = this.attachmentFileList.filter(item => item.uid !== options.file.uid)
        }
      } catch (error) {
        console.error('文件上传失败:', error)
        this.$message.error('文件上传失败')
        // 移除失败的文件
        this.attachmentFileList = this.attachmentFileList.filter(item => item.uid !== options.file.uid)
      }
    },

    handleAttachmentPreview(file) {
      if (file.url) {
        window.open(file.url, '_blank')
      }
    },

    handleAttachmentRemove(file) {
      this.attachmentFileList = this.attachmentFileList.filter(item => item.uid !== file.uid)
    },

    beforeAttachmentUpload(file) {
      const isValidType = /\.(pdf|doc|docx|xls|xlsx|ppt|pptx|txt|jpg|jpeg|png)$/i.test(file.name)
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        this.$message.error('只能上传 PDF、Word、Excel、PPT、图片等格式的文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }

      // 添加到文件列表（显示上传中状态）
      this.attachmentFileList.push({
        name: file.name,
        size: file.size,
        status: 'uploading',
        uid: file.uid,
        fileType: this.getFileType(file.name)
      })

      console.log('准备上传文件:', file.name)
      return true
    },

    handleAttachmentExceed() {
      this.$message.warning('最多只能上传5个文件')
    },

    // 根据文件名获取文件类型
    getFileType(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      const typeMap = {
        'pdf': 'pdf',
        'doc': 'doc',
        'docx': 'docx',
        'xls': 'xls',
        'xlsx': 'xlsx',
        'ppt': 'ppt',
        'pptx': 'pptx',
        'txt': 'txt',
        'jpg': 'jpg',
        'jpeg': 'jpeg',
        'png': 'png'
      }
      return typeMap[extension] || 'unknown'
    },

    // 获取文件图标
    getFileIcon(fileType) {
      const iconMap = {
        'pdf': 'el-icon-document',
        'doc': 'el-icon-document',
        'docx': 'el-icon-document',
        'xls': 'el-icon-s-grid',
        'xlsx': 'el-icon-s-grid',
        'ppt': 'el-icon-picture-outline',
        'pptx': 'el-icon-picture-outline',
        'txt': 'el-icon-document',
        'jpg': 'el-icon-picture-outline',
        'jpeg': 'el-icon-picture-outline',
        'png': 'el-icon-picture-outline'
      }
      return iconMap[fileType] || 'el-icon-document'
    },

    // 格式化文件大小
    formatFileSize(size) {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else {
        return (size / 1024 / 1024).toFixed(2) + ' MB'
      }
    }
  }
}
</script>

<style scoped>
.form-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.project-form {
  padding: 20px 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 附件上传样式 */
.upload-demo {
  width: 100%;
}

.upload-demo .el-upload {
  width: 100%;
}

.upload-demo .el-upload-dragger {
  width: 100%;
  height: 180px;
}

.upload-demo .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-demo .el-upload__tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  margin-top: 7px;
}

/* 文件预览列表样式 */
.file-list-preview {
  margin-top: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
  padding: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #e4e7ed;
}

.file-item:last-child {
  border-bottom: none;
}

.file-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #409EFF;
}

.file-name {
  flex: 1;
  font-size: 14px;
  color: #303133;
  margin-right: 8px;
}

.file-size {
  font-size: 12px;
  color: #909399;
  margin-right: 8px;
}

.file-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
}

.file-status.success {
  color: #67c23a;
  background-color: #f0f9ff;
}

.file-status.uploading {
  color: #409eff;
  background-color: #ecf5ff;
}

.file-status.error {
  color: #f56c6c;
  background-color: #fef0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-card {
    margin: 0 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>